//
//  SearchResultViewController.swift
//  UUCartoon
//
//  Created by Galaxy on 2021/6/28.
//  Copyright © 2021 qykj. All rights reserved.
//

import UIKit
import UICollectionViewLeftAlignedLayout
class SearchResultViewController: BaseViewController {

    var type:CartoonType = .ykmh
    var keyword:String = ""
    var pageNum = 1
    var listArr:[CartoonModel] = []
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = "搜索结果：\(keyword)"
        getListData()
    }

    func getListData(){
        beginProgress()
        DispatchQueue.global().async {
            DataTool.init().getSearchResultData(type: self.type, keyword:self.keyword, page: self.pageNum) { resultArr in
                DispatchQueue.main.async {
                    //TODO: 搜索结果也要存到数据库中
                    self.endProgress()
                    self.mainTable.es.stopPullToRefresh()
                    self.mainTable.es.stopLoadingMore()
                    if !resultArr.isEmpty {
                        self.pageNum += 1
                    }
                    for item in resultArr {
                        item.cartoon_id = SqlTool.init().insertCartoon(model: item)
                    }
                    self.listArr.append(array: resultArr)
                    self.mainTable.listArr = self.listArr
                }
            }
        }
    }
    lazy var mainTable: UUTableView = {
        let tableView = UUTableView.init(frame: .zero, style: .plain)
        view.addSubview(tableView)
        tableView.estimatedRowHeight = 150
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        tableView.register(UINib.init(nibName: "ComicTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "cell")
        tableView.cellForRow {[weak self] (indexPath) in
            let model = self!.listArr[indexPath.row]
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ComicTableViewCell
            cell.model = model
            cell.rankViewConstraintWidth.constant = 40
            return cell
        }
        tableView.cellItemDidSelected {[weak self] (indexPath) in
            let model = self!.listArr[indexPath.row]
            let VC = ChapterViewController.init()
            VC.type = self!.type
            VC.cartoon_id = model.cartoon_id
            VC.detailUrl = model.detailUrl
            self?.navigationController?.pushViewController(VC, animated: true)
        }
        tableView.es.addInfiniteScrolling(animator: footer) {[weak self] in
            self!.getListData()
        }
        return tableView
    }()
}
